home *** CD-ROM | disk | FTP | other *** search
/ MACD 5 / MACD 5.bin / workbench / libs / unixlib.lha / unix / src / regsub.c < prev    next >
C/C++ Source or Header  |  1996-04-27  |  2KB  |  79 lines

  1. /*
  2.  * regsub
  3.  *
  4.  *    Copyright (c) 1986 by University of Toronto.
  5.  *    Written by Henry Spencer.  Not derived from licensed software.
  6.  *
  7.  *    Permission is granted to anyone to use this software for any
  8.  *    purpose on any computer system, and to redistribute it freely,
  9.  *    subject to the following restrictions:
  10.  *
  11.  *    1. The author is not responsible for the consequences of use of
  12.  *        this software, no matter how awful, even if they arise
  13.  *        from defects in it.
  14.  *
  15.  *    2. The origin of this software must not be misrepresented, either
  16.  *        by explicit claim or by omission.
  17.  *
  18.  *    3. Altered versions must be plainly marked as such, and must not
  19.  *        be misrepresented as being the original software.
  20.  */
  21. #include <regexp.h>
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include "regmagic.h"
  25.  
  26. #ifndef CHARBITS
  27. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  28. #else
  29. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  30. #endif
  31.  
  32. /*
  33.  - regsub - perform substitutions after a regexp match
  34.  */
  35. void
  36. regsub(const regexp *prog, const char *source, char *dest)
  37. {
  38.     register char *src;
  39.     register char *dst;
  40.     register char c;
  41.     register int no;
  42.     register int len;
  43.     extern char *strncpy(char *, const char *, size_t);
  44.  
  45.     if (prog == NULL || source == NULL || dest == NULL) {
  46.         regerror("NULL parm to regsub");
  47.         return;
  48.     }
  49.     if (UCHARAT(prog->program) != MAGIC) {
  50.         regerror("damaged regexp fed to regsub");
  51.         return;
  52.     }
  53.  
  54.     src = (char *)source;
  55.     dst = dest;
  56.     while ((c = *src++) != '\0') {
  57.         if (c == '&')
  58.             no = 0;
  59.         else if (c == '\\' && '0' <= *src && *src <= '9')
  60.             no = *src++ - '0';
  61.         else
  62.             no = -1;
  63.          if (no < 0) {    /* Ordinary character. */
  64.              if (c == '\\' && (*src == '\\' || *src == '&'))
  65.                  c = *src++;
  66.              *dst++ = c;
  67.          } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
  68.             len = prog->endp[no] - prog->startp[no];
  69.             (void) strncpy(dst, prog->startp[no], len);
  70.             dst += len;
  71.             if (len != 0 && *(dst-1) == '\0') {    /* strncpy hit NUL. */
  72.                 regerror("damaged match string");
  73.                 return;
  74.             }
  75.         }
  76.     }
  77.     *dst = '\0';
  78. }
  79.